import webapp2
from forest.server.api.templating import template_env
import urlparse
import json
import copy

class BaseHandler(webapp2.RequestHandler):
    data = None
    default_data = {}
    
    def __init__(self, *args, **kwargs):
        super(BaseHandler, self).__init__(*args, **kwargs)

    def _handle_exception(self, exception, debug_mode):
        self.error(500)
        logger.exception(exception)
        self.data['exception'] = exception
        self.data['traceback'] = exception
        self.render_template('templates/500.html')

    def return_error(self, code, template=None):
        self.response.set_status(code)
        self.error(code)
        # TODO: Set status code
        return self.render_template('templates/%s.html' % code)

    def render_template(self, name):
        global template_env
        template = template_env.get_template(name)
        self.response.out.write(template.render(**self.data))
        
    def initialize(self, request, response):
        global template_env
        super(BaseHandler, self).initialize(request, response)
        self.data = copy.copy(self.default_data)
        self.data['request'] = request
        self.data['current_uri'] = urlparse.urlsplit(request.url)
        #i18n.get_i18n().set_locale(locale)

    def return_json(self, data = None, status="ok", message = None):
        resp = {}
        resp['status'] = status
        if message:
            resp['message'] = message
        if data is not None:
            resp['response'] = data
        else:
            resp['response'] = {}
        self.response.write(json.dumps(resp))

    def return_json_error(self, message=None, data=None, code=200):
        if message is None:
            message = "Error! Please refresh your page."
            
        if code != 200:
            self.error(code)
        return self.return_json(message = message, data = data, status = 'error')
                   
